﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XsqTech.SmartOA.Domain.Table;
using XsqTech.SmartOA.Dtos.DTO;
using XsqTech.SmartOA.EFCore.Respository.Base;
using XsqTech.SmartOA.IRespository;
using XsqTech.SmartOA.IRespository.Base;

namespace XsqTech.SmartOA.EFCore.Respository
{
    public class UserRespository : BaseRespository<User>, IUserRespository
    {
        DbContext _db;
        public UserRespository(DbContext db) : base(db)
        {
            _db = db;
        }

        public dynamic UserLogin(string name, string password)
        {
            return _db.Set<User>().FirstOrDefault(x => x.UserName == name && x.UserPassword == password)!;
        }

    }
    public class RolesRespository : BaseRespository<Roles>, IRolesRespository
    {
        DbContext _db;
        public RolesRespository(DbContext db) : base(db)
        {
            _db = db;
        }
        /// <summary>
        /// 给角色添加权限
        /// </summary>
        /// <param name="rid"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public int AddRolePermission(string rid, string pid)
        {
            //先删除原有的权限
            var list = _db.Set<RolePermission>().Where(x => x.RoleId .Equals(rid)).ToList();
            if (list != null)
            {
                _db.Set<RolePermission>().RemoveRange(list); //批删
            }

            var spid = pid.Split(',');
            List<RolePermission> permissions = new List<RolePermission>();
            spid.ToList().ForEach(x =>
            {
                permissions.Add(new RolePermission() {
                    PermissionId =new Guid(x),
                    RoleId = new Guid(rid)
                });
            });

            //批量添加角色权限
            _db.Set<RolePermission>().AddRange(permissions);

            return _db.SaveChanges(); //SaveChanges()方法是自带事务的
        }
        /// <summary>
        /// 获取角色的所有权限
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public List<RolePermission> GetRolePermissions(string rid)
        {
            var list = _db.Set<RolePermission>().Where(x => x.RoleId .Equals( rid)).ToList();
            return list;
        }
    }
        public class RolePermissionRespository : BaseRespository<RolePermission>, IRolePermissionRespository
    {
        public RolePermissionRespository(DbContext db) : base(db)
        {
        }
    }
    public class UserRoleRespository : BaseRespository<UserRole>, IUserRoleRespository
    {
        public UserRoleRespository(DbContext db) : base(db)
        {
        }
    }


}
